package com.lkd.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lkd.common.VMSystem;
import com.lkd.entity.UserEntity;
import com.lkd.service.UserService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
@Component
public class UserJob {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 每日工单量列表初始化
     *
     * @param param
     * @return
     * @throws Exception
     */
    @XxlJob("workCountInitJobHandler")
    public ReturnT<String> workCountInitJobHandler(String param) throws Exception {
        int count = 1;

        if (param != null){
            count = 0;
        }

        // 查询用户列表
        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserEntity::getStatus, 1)
                .ne(UserEntity::getRoleId, 1);
        List<UserEntity> userList = userService.list(queryWrapper);

        // 构建数据（zset）
        String day = LocalDate.now().plusDays(count).format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        for (UserEntity userEntity : userList) {
            String key = VMSystem.REGION_TASK_KEY_PREF + day + userEntity.getRoleCode();
            // 初始化并设置过期时间为两天
            redisTemplate.opsForZSet().add(key, userEntity.getId(), 0);
            redisTemplate.expire(key, Duration.ofDays(2));
        }

        return ReturnT.SUCCESS;
    }


}
